<!-- 习题练习页面 -->
<template>
	<view>
		<!-- 背景图 -->
		<view class="exerc-back" v-if="showPage">
			<image src="/static/exerc/back.png" mode="widthFix" />
		</view>
		<view class="exerc-content" :style="{ bottom: showExerc ? '116upx' : '0' }" v-if="showPage">
			<!-- 顶部选项卡 -->
			<view class="exerc-tab module-back su-sticky">
				<!-- 答题时间 -->
				<text class="exerc-timer">
					<text class="wkfont ticon">&#xe65f;</text>
					<text class="text-time">
						<text v-if="minutes < 10">0{{ minutes }}:</text>
						<text v-else>{{ minutes }}:</text>
						<text v-if="seconds < 10">0{{ seconds }}</text>
						<text v-else>{{ seconds }}</text>
					</text>
				</text>
				<!-- 答题卡 -->
				<text class="exerc-sheet" @click="showExerc = !showExerc">
					<text class="wkfont dticon">&#xe617;</text>
					<text :class="[!showExerc?'select':'']">答题卡</text>
				</text>
			</view>
			<!-- 题目信息 -->
			<swiper class="exerc-swiper" :circular="false" :indicator-dots="true" :current="swiperIndex"
				:autoplay="false" v-if="showExerc" @change="swiperChange">
				<swiper-item v-for="(item, index) in exercList" :key="item.name" :exercConfig="item.name">
					<exerc-item :itemData="item" :itemIndex="index" :exerc-config="exercConfig" @select="itemSelect" />
				</swiper-item>
			</swiper>
			<answer-sheet v-else :exerc-list="exercList" @select="sheetSelect" />
		</view>
		<!-- 底部提交按钮 -->
		<view class="exerc-bottom su-border2" v-if="showExerc && showPage">
			<button class="su-button" @click="submitExerc">提交练习</button>
		</view>
		<!-- 提交反馈 -->
		<result v-if="showResult" :sub-info="submitData" />
	</view>
</template>
<script>
	/**
	 * 习题练习页面
	 */

	// 加载服务器数据
	const db = uniCloud.database()
	let abu_answer_activity_db = db.collection('abu-answering-activity');
	let abu_question_info_db = db.collection('abu-question-info');
	let abu_question_option_db = db.collection('abu-question-option');
	let abu_answer_log_db = db.collection('abu-answer-log');

	import exercItem from './comp/exerc-card.vue'
	import answerSheet from './comp/answer-sheet.vue'
	import result from './result.vue'
	// import mockJson from './mock/exerc.json'
	import {
		startCountdown,
		expTopic,
		handleSubmit
	} from './js/exerc-utils.js'
	export default {
		components: {
			exercItem,
			answerSheet,
			result
		},
		data() {
			return {
				// 用户数据
				abu_answer_activity_id: '',
				dati_list: [],
				showPage: false,
				showResult: false,
				showExerc: true,
				// 题目列表
				exercList: [],
				exercTimer: null,
				// 习题配置信息
				exercConfig: {},
				minutes: 0,
				seconds: 0,
				// 当前索引
				swiperIndex: 0,
				canback: false,
				submitData: {}
			}
		},
		async onLoad(params) {
			this.abu_answer_activity_id = '65facb399755e3283019defb'
			if (params && params.id) {
				this.abu_answer_activity_id = params.id;
			}
			uni.showLoading({
				title: '题目正在玩命的加载中.....',
				mask: true
			});
			await this.load_data();
			await this.queryExerc()
			uni.hideLoading()
		},
		onUnload() {
			clearInterval(this.exercTimer)
		},
		onNavigationBarButtonTap() {
			this.$as.message('左右滑动可切换题目', 'info')
		},
		onBackPress() {
			if (this.canback) return false
			else {
				return this.showBackDialog(), true
			}
		},
		computed: {
			isAnswered() {
				let result = true
				this.exercList.forEach(p => {
					if (!p.select) {
						result = false
					}
				})
				return result
			}
		},
		methods: {
			async load_data() {
				const res = await abu_answer_activity_db.where({
					_id: this.abu_answer_activity_id
				}).get({
					getOne: true
				});

				console.log(res.result.data);
				let timu = res.result.data;

				const res1 = await abu_question_info_db.where({
					belong_hd: res.result.data._id
				}).get();

				// console.log(res1.result.data);

				let qs = res1.result.data;

				for (let i = 0; i < qs.length; i++) {
					const item = qs[i];
					const d = await abu_question_option_db.where({
						belong_qs: item._id
					}).get();
					qs[i] = {
						"options": {
							...item,
							"optionItems": d.result.data,
						},
						"type": "radio",
						"icon": "radio-field",
						"formItemFlag": true,
					};

					// 对获取的数据进行处理，你可以根据需要对返回结果进行进一步处理
				}

				this.dati_list = {
					// ...timu,
					"widgetList": [{
						"type": "radio-group",
						"category": "container",
						"icon": "radio-group",
						"widgetList": qs
					}],
					"formConfig": {
						"labelPosition": "top",
						"size": "",
						"labelAlign": "label-left-align",
						"layoutType": "Pad",
						"exercId": "mockexerc1",
						"exercTitle": timu.title,
						"exercCount": timu.count,
						"exercScore": timu.score,
						"exercTime": timu.time_limit,
						"createTime": timu.start_date,
						"createPerson": "管理员",
						"labelWidth": 140
					}
				};

				console.log(this.dati_list);
			},
			queryExerc() {
				// this.handleExerc(mockJson)
				this.handleExerc(this.dati_list)
			},
			handleExerc(exercJson) {
				this.exercConfig = exercJson['formConfig']
				// 开始倒计时 
				const {
					exercTime,
					exercTitle,
					exercId,
					exercScore,
					exercCount
				} = this.exercConfig
				if (exercTitle) {
					uni.setNavigationBarTitle({
						title: exercTitle
					})
				}
				this.minutes = exercTime
				// 处理题目
				let tmpList = []
				expTopic(exercJson['widgetList'], tmpList)
				this.exercList = tmpList
				// 弹出确认框

				uni.showModal({
					title: '温馨提示',
					content: `习题加载成功，习题练习时间为` +
						`${exercTime}分钟，确认后将开始倒计时。`,
					confirmColor: '#0B56B1',
					success: (e) => {
						if (e.confirm) {
							this.showPage = true
							Object.assign(this.submitData, {
								start_time: new Date().getTime(),
								total_score: parseInt(exercScore),
								total_count: exercCount,
								exerc_name: exercTitle,
								exerc_id: exercId,
								total_time: exercTime
							})
							startCountdown.apply(this)
						}
						if (e.cancel) {
							uni.navigateBack()
						}
					}
				})
			},
			// 题目选择
			itemSelect(data) {

				// 在父组件里面赋值
				this.exercList[data.index].select = data.item.value
				//检验值
				console.log(data.item);
				console.log(this.exercList);
				if (data.index + 1 === this.exercConfig.exercCount)
					return
				this.swiperIndex = data.index + 1
			},
			showBackDialog() {
				uni.showModal({
					title: '温馨提示',
					content: '当前尚未提交习题练习，退出将导致答题数据丢失，是否确认要退出？',
					success: function(res) {
						if (res.confirm) {
							// 在这里添加确认退出时的逻辑代码
						}
					}
				});

				this.canback = true
				uni.navigateBack()
			},
			// 提交题目
			submitExerc() {
				let sbExerc = () => {
					let subData = handleSubmit.apply(this);
					abu_answer_log_db.add({
						complete_time: subData.start_time,
						score: parseInt(subData.current_score),
						quiz_id: subData.exerc_name,
						data: this.dati_list,
						subData:subData

					}).then(res => {
						uni.showToast({
							title: '提交成功',
							icon: 'none'
						});
					}).catch(e => {
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					})
					console.log(subData);
					this.canback = true
					this.showPage = false
					// this.showResult = false
					this.showResult = true
				}
				if (!this.isAnswered) {
					uni.showModal({
						title: '温馨提示',
						content: '当前练习题还没有做完，是否继续提交？',
						success: function(res) {
							if (res.confirm) {
								sbExerc();
							}
						}
					});
				} else {
					sbExerc();
				}

			},
			swiperChange(event) {
				const {
					current
				} = event.detail
				this.swiperIndex = current
			},
			// 答题卡选择
			sheetSelect(index) {
				this.swiperIndex = index
				this.showExerc = true
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>